<?php
/* 预约设置相关操作控制器 */
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ReservationSetController extends HomeController
{
    //菜单操作权限，1=新增 2=删除 3=修改 4=查看
    public $weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];

    //获取列表
    public function list(Request $request)
    {
        try {
            // 分页参数
            $page = $request->input('page', 1);
            $limit = $request->input('limit', 10);
            $search_name = $request->input('search_name');

            $field = ['id','name','start_date','end_date','am_start_time','am_end_time','pm_start_time','pm_end_time', 'max_lead', 'slot_length','max_capacity','weekdays','status'];

            $condition = [];
            if ($search_name) {
                $condition[] = ['name', 'like', '%' . $search_name . '%'];
            }
            //默认查询未删除的数据is_delete=0
            $condition[] = ['is_delete', '=', 0];
            
            // 查询数据表，默认查询未删除的数据is_delete=0
            $data = DB::table('reservation_set')->where($condition)->select($field)->orderBy('created_at','desc')->offset(($page - 1) * $limit)->limit($limit)->get();

            //遍历$data，把weekdays字段的值转换为数组
            foreach ($data as $key => $val) {
                $arr = [];
                //把weekdays字段的值转换为数组，str_split()函数把字符串转换为数组，参数2为数组的长度，默认1长度
                $weekdays = str_split($val->weekdays);
                //遍历$weekdays，根据索引值获取对应的星期
                foreach ($weekdays as $k => $v) {
                    if ($v == '0') {
                        $arr[] = $this->weekdays[$k];
                    }
                }
                //把$arr转换为字符串，用逗号隔开
                $data[$key]->weekdays = implode(',', $arr);
            }

            // 统计总记录数
            $count = DB::table('reservation_set')->count();

            return response()->json([
                'code' => HTTP_OK,
                'message' => HTTP_OK_MESSAGE,
                'data' => $data,
                'count' => $count,
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取预约设置列表失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取预约设置列表失败',
                'data' => null
            ]);
        }
    }

    //添加
    public function insert(Request $request)
    {
        try {
            //声明数组，默认所有天都不开启，根据参数把选择的天的状态改为1
            $arr = [1 => '0',2 => '0',3 => '0',4 => '0',5 => '0',6 => '0',7 => '0'];
            $weekdays = $request->input('weekdays');
            if ($weekdays) {
                foreach ($weekdays as $val) {
                    //根据参数把选中的天的状态改为1
                    $arr[$val] = '1';
                }
                $str = implode('', $arr);
            } else {
                //没有选择则直接把所有天都设为0
                $str = '0000000';
            }

            //把日期分割成数组
            $arr = explode('~', $request->input('date'));
            if (trim($arr[1]) <= trim($arr[0])) {
                return response()->json([
                    'code' => HTTP_ERROR,
                    'message' => '结束日期不能小于开始日期',
                ]);
            }

            //接受参数并组装成数组
            $data = [];
            $data['name'] = $request->input('name');
            $data['start_date'] = trim($arr[0]);
            $data['end_date'] = trim($arr[1]);
            $data['am_start_time'] = $request->input('am_start_time');
            $data['am_end_time'] = $request->input('am_end_time') ? : NULL;
            $data['pm_start_time'] = $request->input('pm_start_time') ? : NULL;
            $data['pm_end_time'] = $request->input('pm_end_time') ? : NULL;
            $data['max_lead'] = $request->input('max_lead');
            $data['slot_length'] = $request->input('slot_length');
            $data['max_capacity'] = $request->input('max_capacity');
            $data['weekdays'] = $str;
            $data['status'] = $request->input('status');
            //添加到数据表
            DB::table('reservation_set')->insert($data);

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('添加预约设置失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '添加预约设置失败',
                'data' => null
            ]);
        }
    }

    //删除
    public function delete(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            //这里使用逻辑删除，把删除状态is_delete改为1，status状态改为2表示不生效
            DB::table('reservation_set')->where('id', $id)->update(['is_delete' => 1, 'status' => 2]);

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('删除预约设置失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '删除预约设置失败',
                'data' => null
            ]);
        }
    }


    //修改
    public function update(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            //声明数组，默认所有天都不开启，根据参数把选中的天的状态改为1
            $arr = [1 => '0',2 => '0',3 => '0',4 => '0',5 => '0',6 => '0',7 => '0'];
            $weekdays = $request->input('weekdays');
            if ($weekdays) {
                foreach ($weekdays as $val) {
                    //根据参数把选中的天的状态改为1
                    $arr[$val] = '1';
                }
                $str = implode('', $arr);
            } else {
                //没有选择则直接把所有天都设为0
                $str = '0000000';
            }

            //把日期分割成数组
            $arr = explode('~', $request->input('date'));
            if (trim($arr[1]) <= trim($arr[0])) {
                return response()->json([
                    'code' => HTTP_ERROR,
                    'message' => '结束日期不能小于开始日期',
                ]);
            }

            //接受参数并组装成数组
            $data = [];
            $data['name'] = $request->input('name');
            $data['start_date'] = trim($arr[0]);
            $data['end_date'] = trim($arr[1]);
            $data['am_start_time'] = $request->input('am_start_time');
            $data['am_end_time'] = $request->input('am_end_time') ? : NULL;
            $data['pm_start_time'] = $request->input('pm_start_time') ? : NULL;
            $data['pm_end_time'] = $request->input('pm_end_time') ? : NULL;
            $data['max_lead'] = $request->input('max_lead');
            $data['slot_length'] = $request->input('slot_length');
            $data['max_capacity'] = $request->input('max_capacity');
            $data['weekdays'] = $str;
            $data['status'] = $request->input('status');
            //修改数据到数据表
            DB::table('reservation_set')->where('id', $id)->update($data);

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('修改预约设置失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '修改预约设置失败',
                'data' => null
            ]);
        }
    }

    //详情
    public function detail(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            //根据id查询详情
            $data = DB::table('reservation_set')->where('id', $id)->first();
            $arr = [];
            //把weekdays字段的值转换为数组，str_split()函数把字符串转换为数组，参数2为数组的长度，默认1长度
            $weekdays = str_split($data->weekdays);
            //遍历数组，把值为1的下标添加到数组中
            foreach ($weekdays as $key => $val) {
                if ($val == '1') {
                    $arr[] = $key + 1;
                }
            }
            //把数组转换为字符串
            $data->weekdays = $arr;
            $data->date = $data->start_date . ' ~ ' . $data->end_date;

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE,'data' => $data]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取预约设置详情失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取预约设置详情失败',
                'data' => null
            ]);
        }
    }

}
